import { Controller, Get, Res } from "@nestjs/common";
import { AppService } from "./app.service";
import { createCanvas } from "canvas";
import * as echarts from "echarts";
const path = require('path');
const fs = require('fs');
import * as ExcelJS from "exceljs";
import { Response } from 'express';
@Controller()
export class AppController {
  constructor(private readonly appService: AppService) {
  }

  @Get()
  async getHello(@Res() res: Response) {
    const canvas = createCanvas(600, 400);
    const chart = echarts.init(canvas as any);  // 强制转换为 `any`
    const option =  {
      tooltip: {
        trigger: 'item'
      },
      legend: {
        top: '5%',
        left: 'center'
      },
      series: [
        {
          name: 'Access From',
          type: 'pie',
          radius: ['40%', '70%'],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 10,
            borderColor: '#fff',
            borderWidth: 2
          },
          label: {
            show: false,
            position: 'center'
          },
          emphasis: {
            label: {
              show: true,
              fontSize: 40,
              fontWeight: 'bold'
            }
          },
          labelLine: {
            show: false
          },
          data: [
            { value: 1048, name: 'Search Engine' },
            { value: 735, name: 'Direct' },
            { value: 580, name: 'Email' },
            { value: 484, name: 'Union Ads' },
            { value: 300, name: 'Video Ads' }
          ]
        }
      ]
    };

    chart.setOption(option);

    // 获取图表的图片 buffer
    const chartBuffer = canvas.toBuffer('image/png');

    // 创建 Excel 文件
    const workbook = new ExcelJS.Workbook();
    const worksheet = workbook.addWorksheet('Sheet 1');
    worksheet.columns = [
      { header: '名称', key: 'name' },
      { header: '值', key: 'value' }
    ];
    worksheet.addRow({ name: '数据1', value: 30 });
    worksheet.addRow({ name: '数据2', value: 50 });
    worksheet.addRow({ name: '数据3', value: 80 });

    // 将图表的 buffer 直接插入到 Excel 文件中
    const imageId = workbook.addImage({
      buffer: chartBuffer,  // 使用 buffer 而不是文件路径
      extension: 'png',  // 图片格式
    });

    // 插入图片
    worksheet.addImage(imageId, 'A5:G20');

    // 设置合法的文件名，确保不包含非法字符
    const fileName = 'test.xlsx';
    const encodedFileName = encodeURIComponent(fileName);  // URL 编码

    // 返回 Excel 文件
    res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
    res.setHeader('Content-Disposition', `attachment; filename="${encodedFileName}"`);
    await workbook.xlsx.write(res);  // 写入文件并返回
    res.end();
  }
}
